package com.xu.t1.middleware.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 实现redis过期key分发的组件类
 * 根据键类型找到对应的处理器
 *
 * @author xu
 *
 */

@Component
public class RedisExpiredEventDispatcher {

    private final Map<String, ExpiredKeyHandler> handlerMap = new HashMap<>();

    @Autowired
    public RedisExpiredEventDispatcher(List<ExpiredKeyHandler> handlers) {
        for (ExpiredKeyHandler handler : handlers) {
            Component annotation = handler.getClass().getAnnotation(Component.class);
            if (annotation != null && !annotation.value().isEmpty()) {
                handlerMap.put(annotation.value(), handler);
            }
        }
    }

    public void dispatch(String expiredKey) {
        String[] parts = expiredKey.split(":");
        if (parts.length == 0) return;

        String type = parts[0];
        ExpiredKeyHandler handler = handlerMap.get(type);

        if (handler != null) {
            handler.handle(parts);
        } else {
            System.err.println("未找到处理器: " + type + ", key: " + expiredKey);
        }
    }
}